/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.chipchip.database.tables;

import com.chipchip.database.DBManager;
import com.chipchip.database.objects.DOUserMap;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 *
 * @author Tri
 */
public class DTUserMap {
    private static DTUserMap instance = null;
    public static DTUserMap sharedInstance() {
        if(instance == null) {
            instance = new DTUserMap();
        }
        return instance;
    }
    public static final String TABLE_NAME = "UserMaps";
    
    MongoOperations m_mongoOperations;
    private DTUserMap() {
        m_mongoOperations = DBManager.sharedInstance().mongoOperations();
    }
    
    public void insert(DOUserMap map) {
        m_mongoOperations.save(map, TABLE_NAME);
    }
    
    public boolean update(DOUserMap map) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOUserMap.KEY_MAP_ID).is(map.getMapID()));
        DOUserMap userResult = m_mongoOperations.findOne(query, DOUserMap.class);
        if (userResult != null) {
            Update update = new Update();
            update.set(DOUserMap.KEY_BET_MONEY, map.betMoney);
            update.set(DOUserMap.KEY_COMPLETE_STEPS, map.completeStep);
            update.set(DOUserMap.KEY_COMPLETE_TIME, map.completeTime);
            update.set(DOUserMap.KEY_FIVE_STAR, map.fiveStar);
            update.set(DOUserMap.KEY_FOUR_STAR, map.fourStar);
            update.set(DOUserMap.KEY_THREE_STAR, map.threeStar);
            update.set(DOUserMap.KEY_TWO_STAR, map.twoStar);
            update.set(DOUserMap.KEY_ONE_STAR, map.oneStar);
            update.set(DOUserMap.KEY_MAP_NAME, map.mapName);
            update.set(DOUserMap.KEY_MATRIX, map.matrix);
            update.set(DOUserMap.KEY_OBSTACLES_LIST, map.obstaclesList);
            
            m_mongoOperations.updateFirst(query, update, DOUserMap.class);
            return true;
        }
        return false;
    }
    
    public DOUserMap getUserMap(String mapID) {
        DOUserMap map = null;
        Query query = new Query();
        query.addCriteria(Criteria.where(DOUserMap.KEY_MAP_ID).is(mapID));
        map = m_mongoOperations.findOne(query, DOUserMap.class);
        return map;
    }
}
